import { defineStore } from 'pinia';
import { storage } from './../composables/storage';
import { ElMessage, ElMessageBox } from 'element-plus';
import { router } from '../router/index';
import { post, postWithToken } from '~/composables/utils';
import { useRouteStore } from './route';

// 第一个参数是应用程序中 store 的唯一 id
export const useUsersStore = defineStore('users', {
    state : () => {
        return {
            token: storage.get('token'),
            userId: storage.get('userId'),
            realName: storage.get('realName'),
            email: storage.get('email'),
            permissionUrl: storage.get('permissionUrl'),
            userName: storage.get('userName')
        };
    },
    actions: {
        async login(params: any) {
          const response =  await post('/user/login', params);
          if (response.code == 200) {
            ElMessage.success('登录成功');
            this.token = response.data.token;
            this.userId = response.data.userId;
            this.realName = response.data.realName;
            this.email = response.data.email;
            this.permissionUrl = response.data.permissionUrl;
            this.userName = response.data.username;
            storage.set('token', response.data.token);
            storage.set('userId', response.data.userId);
            storage.set('realName', response.data.realName);
            storage.set('email', response.data.email);
            storage.set('permissionUrl', response.data.permissionUrl);
            storage.set('userName', response.data.username);
            router.push((router.currentRoute.value.query?.redirect || '/topic/randomPractice') as string);
            // const routerStore = useRouteStore();
            // await routerStore.initRoute(response.data.permissionUrl);
            // router.push('/topic/randomPractice');
          } else {
            ElMessage.error(response.msg);
          }
        },
        logout() {
          ElMessageBox.confirm('您确定要退出登录吗？', '提示', {type: 'warning'})
            .then(() => {
              postWithToken('/user/logout');
              this.clearStorage();
            })
            .catch(() => {});
        },
        clearStorage() {
          console.log('用户未登录');
          storage.remove('token');
          storage.remove('userId');
          storage.remove('realName');
          storage.remove('email');
          storage.remove('permissionUrl');
          router.push('/');
          this.$reset();
          const routerStore = useRouteStore();
          routerStore.isInitRoute = false;
        }
    }
});
